package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetaliMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;

    /*
    * 用户下单
     */
    @Override
    @Transactional  // 开启事务
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {

        log.info("用户下单：{}", dto.getAddressBookId());

        //查询地址对应的信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());

        log.info("查询地址对应信息：{},id为：{},线程id为:{}", addressBook, dto.getAddressBookId(),BaseContext.getCurrentId());
        if(addressBook == null){
            throw new OrderBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //查询下单人的信息
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);
        if(user == null){
            throw new OrderBusinessException(MessageConstant.USER_NOT_LOGIN);
        }

        //查询购物车数据-->自己名下的购物车数据
        List<ShoppingCart> cartList = shoppingCartMapper.list(userId);
        if(cartList == null || cartList.size() == 0){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //1.构造订单数据，存入orders表
        Orders orders = new Orders();
        BeanUtils.copyProperties(dto, orders);
        //补充缺失的属性值
        orders.setNumber(System.currentTimeMillis()+"");  //订单编号
        orders.setStatus(Orders.PENDING_PAYMENT);         //订单状态
        orders.setUserId(userId);     //用户id
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setConsignee(addressBook.getConsignee());  //收货人
        orders.setUserName(user.getName());               //下单人
        ordersMapper.insert(orders);

        //2.构造订单明细数据，存入orderDetail表
        List<OrderDetail> orderDetailList = new ArrayList<>();
        cartList.forEach(cart -> {
            //遍历购物车数据,赋值给订单明细
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail, "id");
            //关联订单id
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });

        //批量插入订单明细
        orderDetailMapper.insertBatch(orderDetailList);

        //3.清空购物车-->自己名下的购物车数据
        shoppingCartMapper.clean(userId);

        //4.构造OrderSubmitVO并返回
        OrderSubmitVO vo = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return vo;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        /*Long userId = BaseContext.getCurrentId();
        User user = userMapper.selectById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
                                                 );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;*/

        ////////////////////////////////////////////////////////////////////
        //模拟支付成功-----修改订单状态
        //业务处理，修改订单状态、来单提醒
        paySuccess(ordersPaymentDTO.getOrderNumber());
        //返回空对象就可以
        return new OrderPaymentVO();
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = ordersMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        ordersMapper.update(orders);

        //////////////////////////////////////////////
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        ///////////////////////////////////////////////////
    }

    /**
     * 历史订单查询
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult historyOrders(Integer page, Integer pageSize, Integer status) {
        //设置分页参数
        PageHelper.startPage(page, pageSize);

        //用户登录id
        Long userId = BaseContext.getCurrentId();

        OrdersPageQueryDTO dto = new OrdersPageQueryDTO();
        dto.setStatus(status);
        dto.setUserId(userId);

        //分页条件查询，第一个返回对象
        Page<Orders> pageInfo = ordersMapper.pageQuery(dto);

        //第二个返回对象
        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (pageInfo != null && pageInfo.getTotal() > 0) {
            for (Orders orders : pageInfo) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(pageInfo.getTotal(), list);

    }

    /**
     * 查询订单详细信息
     * @param id
     * @return
     */
    @Override
    public OrderVO details(Long id) {
        //创建订单VO对象
        OrderVO orderVO = new OrderVO();

        //1.查询订单信息
        Orders orders = ordersMapper.selectById(id);
        BeanUtils.copyProperties(orders, orderVO);
        log.info("查询到的订单信息：{},订单号：{}", orders,orders.getId());

        //2.查询订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(orders.getId());

        //订单详情可能有多个值，循环赋值给orderVO
        orderVO.setOrderDetailList(orderDetailList);

        log.info("查询出来的订单详情：{}",orderVO);


        return orderVO;
    }

    /**
     * 订单取消
     * @param id
     */
    @Override
    public void cancel(Long id) {

        //查询订单信息
        Orders orders = ordersMapper.selectById(id);
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //判断订单是否可取消(判断状态)
        if(orders.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //如果订单处于待接单状态（2），多了一步设置退款状态
        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            orders.setPayStatus(Orders.REFUND);
        }

        log.info("当前状态为：{},对比状态为：{}",orders.getStatus(),(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)));

        //补充其他字段
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        ordersMapper.update(orders);

    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //根据订单id查到之前的订单信息和订单明细
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);

        if(orderDetailList == null || orderDetailList.size() == 0){
            throw new OrderBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //创建新的订单
        orderDetailList.forEach(orderDetail -> {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            //补充用户id和创建时间字段
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);
        });
    }

    /**
     * 订单催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //查询订单是否存在
        Orders orders = ordersMapper.selectById(id);
        if(orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        //基于WebSocket实现催单
        Map map = new HashMap();
        map.put("type", 2);//2代表用户催单
        map.put("orderId", id);
        map.put("content", "订单号：" + orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
